package hash_table;

import java.util.Scanner;

public class HashTableDemo {
    public static void main(String[] args) {
        HashTable table = new HashTable(7);
        String key = "";
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("add: 添加");
            System.out.println("show: 显示");
            System.out.println("exit: 退出");

            key = scanner.next();
            switch (key) {
                case "add":
                    System.out.println("输入id");
                    int id = scanner.nextInt();
                    System.out.println("输入名字");
                    String name = scanner.next();
                    table.add(new Employee(id, name));
                    break;
                case "show":
                    table.showAll();
                    break;
                case "exit":
                    scanner.close();
                    System.exit(0);
            }
        }
    }
}

class HashTable {
    private int size;
    private EmployeeLinkedList[] arr;

    HashTable(int size) {
        this.size = size;
        // 初始化数组
        arr = new EmployeeLinkedList[size];
        // 分别初始化数组里的每一个链表元素
        for (int i = 0; i < size; i++) {
            arr[i] = new EmployeeLinkedList();
        }
    }

    public void add(Employee e) {
        // 根据员工id获取应加入的链表在arr中的索引
        int index = hashFunction(e.id);
        // 添加
        arr[index].add(e);
    }

    // 最简单的哈希函数：取模
    private int hashFunction(int id) {
        return id % size;
    }

    // 输出所有链表
    public void showAll() {
        for (int i = 0; i < size; i++) {
            arr[i].show(i);
        }
    }
}

class Employee {
    public int id;
    public String name;
    public Employee next;

    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

class EmployeeLinkedList {
    private Employee head;

    // 添加雇员
    public void add(Employee employee) {
        // 如果链表为空
        if (head == null) {
            head = employee;
            return;
        }
        // 注意此处head即位第一个节点
        Employee cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = employee;
    }

    // 输出链表
    public void show(int no) {
        System.out.printf("%d => ", no);
        if (head == null) {
            System.out.println("链表空\n");
            return;
        }
        Employee cur = head;
        while (cur != null) {
            System.out.printf("%s[%d]  ", cur.name, cur.id);
            cur = cur.next;
        }
        System.out.println();
        System.out.println();
    }

}
